package lib

import (
	"GameServer/Common/data"
	"GameServer/Game/errors"
	"GameServer/Game/m"
	"encoding/json"
)

type Extend struct {
	Tid int64 `json:"tid"`
}

// 麦驰自研 分发商品
func MCDispenseCommodity(from string, u *m.User, productId string, exten string, UnionSendRedPacketReq func(packId int64), PSend func(interface{}) error) (uProp *m.UpdateProp, resGoodsList []*m.Goods, boxResList []*m.BoxRes, err error) {
	// productId商品id，读取配表，获取道具
	tplLst, ok := data.Filters("PaidPropsPacks", func(val interface{}) bool {
		valT := val.(data.PaidPropsPack)
		return valT.ProductIdIOS == productId || valT.ProductIdGP == productId
	})
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到该配置表PaidPropsPacks")
		return
	}
	if tplLst == nil || len(tplLst) == 0 {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到该配置表PaidPropsPacks的产品 "+productId)
		return
	}
	var pppT data.PaidPropsPack
	if len(tplLst) > 1 {
		for _, item := range tplLst {
			itemT := item.(data.PaidPropsPack)
			if int64(itemT.Typ) == data.PaidPropsEnum.ActPack {
				pppT = itemT
				break
			}
		}
	} else {
		pppT = tplLst[0].(data.PaidPropsPack)
	}
	tid := int64(pppT.Id)
	switch int64(pppT.Typ) {
	case data.PaidPropsEnum.GemsCharge:
		uProp, resGoodsList, boxResList, err = BuyDiamond(from, u, tid, PSend)
		RecordShopBuyItem(u, tid)
	case data.PaidPropsEnum.DailyPack:
		_, _, uProp, resGoodsList, boxResList, err = BuyDailyGift(from, u, PSend)
	case data.PaidPropsEnum.ActPack, data.PaidPropsEnum.PetPack:
		var extenT Extend
		err = json.Unmarshal([]byte(exten), &extenT)
		if err != nil {
			return
		}
		_, _, uProp, resGoodsList, boxResList, err = BuyActPack(from, u, extenT.Tid, UnionSendRedPacketReq, PSend)
	case data.PaidPropsEnum.BossPack:
		var extenT Exten1
		err = json.Unmarshal([]byte(exten), &extenT)
		if err != nil {
			return
		}
		_, _, uProp, resGoodsList, boxResList, err = BuyBossPack(from, u, extenT.PackId, PSend)
	}
	if err != nil {
		return
	}
	return
}
